<template>
  <div class="products">
    <div class="header">
      <h2>商品管理</h2>
      <div class="header-actions">
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>导出
        </el-button>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加商品
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="filter-section">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="商品名称">
          <el-input v-model="filterForm.keyword" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="filterForm.categoryId" placeholder="全部分类" clearable>
            <el-option
              v-for="category in productStore.categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态">
          <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
            <el-option label="在售" value="on" />
            <el-option label="已下架" value="off" />
            <el-option label="已售出" value="sold" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格区间">
          <el-input-number 
            v-model="filterForm.minPrice" 
            :min="0" 
            placeholder="最低价"
            style="width: 130px"
          />
          <span class="mx-2">-</span>
          <el-input-number 
            v-model="filterForm.maxPrice" 
            :min="0" 
            placeholder="最高价"
            style="width: 130px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品表格 -->
    <el-table
      v-loading="productStore.loading"
      :data="displayProducts"
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column label="商品图片" width="120">
        <template #default="{ row }">
          <el-image
            style="width: 80px; height: 80px"
            :src="row.images[0]"
            fit="cover"
            :preview-src-list="row.images"
          />
        </template>
      </el-table-column>

      <el-table-column prop="title" label="商品名称" />
      
      <el-table-column label="价格" width="100">
        <template #default="{ row }">
          <span class="price">¥{{ row.price }}</span>
        </template>
      </el-table-column>

      <el-table-column label="成色" width="100">
        <template #default="{ row }">
          <el-tag :type="getConditionType(row.condition)">
            {{ row.condition }}成新
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="配送方式" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.shippingMethod === 'express'" type="success">快递</el-tag>
          <el-tag v-if="row.shippingMethod === 'self'" type="warning">自提</el-tag>
          <el-tag v-if="row.shippingMethod === 'both'" type="info">快递/自提</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button size="small" @click="handleViewDetail(row)">查看</el-button>
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="row.status === 'on' ? 'warning' : 'success'"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 'on' ? '下架' : '上架' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredProducts.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formType === 'add' ? '添加商品' : '编辑商品'"
      width="60%"
    >
      <el-form
        ref="formRef"
        :model="productForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="productForm.title" />
        </el-form-item>

        <el-form-item label="商品图片" prop="images">
          <el-upload
            v-model:file-list="fileList"
            action="/api/upload"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="productForm.price" :min="0" :precision="2" />
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="productForm.categoryId">
            <el-option
              v-for="category in productStore.categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品成色" prop="condition">
          <el-slider
            v-model="productForm.condition"
            :min="1"
            :max="10"
            :marks="{
              1: '1成新',
              5: '5成新',
              10: '全新'
            }"
          />
        </el-form-item>

        <el-form-item label="配送方式" prop="shippingMethod">
          <el-radio-group v-model="productForm.shippingMethod">
            <el-radio label="express">快递</el-radio>
            <el-radio label="self">自提</el-radio>
            <el-radio label="both">快递和自提</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="运费" prop="shippingFee">
          <el-input-number 
            v-model="productForm.shippingFee" 
            :min="0"
            :precision="2"
            :disabled="productForm.shippingMethod === 'self'"
          />
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 商品详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="商品详情"
      width="70%"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商品名称">{{ currentProduct?.title }}</el-descriptions-item>
        <el-descriptions-item label="商品价格">¥{{ currentProduct?.price }}</el-descriptions-item>
        <el-descriptions-item label="商品分类">
          {{ getCategoryName(currentProduct?.categoryId) }}
        </el-descriptions-item>
        <el-descriptions-item label="商品状态">
          <el-tag :type="getStatusType(currentProduct?.status || '')">
            {{ getStatusText(currentProduct?.status || '') }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="商品成色">
          <el-tag :type="getConditionType(currentProduct?.condition || 0)">
            {{ currentProduct?.condition }}成新
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="配送方式">
          {{ getShippingMethodText(currentProduct?.shippingMethod) }}
        </el-descriptions-item>
        <el-descriptions-item label="运费">¥{{ currentProduct?.shippingFee }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(currentProduct?.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="商品图片" :span="2">
          <el-image
            v-for="(img, index) in currentProduct?.images"
            :key="index"
            :src="img"
            fit="cover"
            style="width: 100px; height: 100px; margin-right: 10px;"
            :preview-src-list="currentProduct?.images"
          />
        </el-descriptions-item>
        <el-descriptions-item label="商品描述" :span="2">
          {{ currentProduct?.description }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { Plus, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useProductStore } from '@/stores/product'
import type { Product } from '@/types/product'

const productStore = useProductStore()

// 表单相关
const dialogVisible = ref(false)
const formType = ref<'add' | 'edit'>('add')
const formRef = ref()
const fileList = ref([])

const productForm = reactive({
  id: 0,
  title: '',
  images: [] as string[],
  price: 0,
  description: '',
  categoryId: 1,
  userId: 1,
  condition: 10,
  shippingMethod: 'express' as 'express' | 'self' | 'both',
  shippingFee: 0,
  status: 'on' as 'on' | 'off' | 'sold'
})

const rules = {
  title: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  images: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
  price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
  description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }]
}

// 状态和成色的展示处理
const getStatusType = (status: string) => {
  const types = {
    on: 'success',
    off: 'info',
    sold: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts = {
    on: '在售',
    off: '已下架',
    sold: '已售出'
  }
  return texts[status] || status
}

const getConditionType = (condition: number) => {
  if (condition === 10) return 'success'
  if (condition >= 7) return ''
  if (condition >= 4) return 'warning'
  return 'danger'
}

// 搜索筛选相关
const filterForm = reactive({
  keyword: '',
  categoryId: '',
  status: '',
  minPrice: undefined as number | undefined,
  maxPrice: undefined as number | undefined
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 详情相关
const detailVisible = ref(false)
const currentProduct = ref<Product | null>(null)

// 计算过滤后的商品列表
const filteredProducts = computed(() => {
  return productStore.products.filter(product => {
    const matchKeyword = !filterForm.keyword || 
      product.title.toLowerCase().includes(filterForm.keyword.toLowerCase())
    const matchCategory = !filterForm.categoryId || 
      product.categoryId === filterForm.categoryId
    const matchStatus = !filterForm.status || 
      product.status === filterForm.status
    const matchPrice = (!filterForm.minPrice || product.price >= filterForm.minPrice) &&
      (!filterForm.maxPrice || product.price <= filterForm.maxPrice)
    
    return matchKeyword && matchCategory && matchStatus && matchPrice
  })
})

// 计算当前页显示的商品
const displayProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredProducts.value.slice(start, end)
})

// 处理函数
const handleAdd = () => {
  formType.value = 'add'
  Object.assign(productForm, {
    id: 0,
    title: '',
    images: [],
    price: 0,
    description: '',
    categoryId: 1,
    userId: 1,
    condition: 10,
    shippingMethod: 'express',
    shippingFee: 0,
    status: 'on'
  })
  fileList.value = []
  dialogVisible.value = true
}

const handleEdit = (row: Product) => {
  formType.value = 'edit'
  Object.assign(productForm, row)
  fileList.value = row.images.map((url, index) => ({
    name: `image-${index}`,
    url
  }))
  dialogVisible.value = true
}

const handleDelete = (row: Product) => {
  ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
    type: 'warning'
  }).then(() => {
    productStore.deleteProduct(row.id)
    ElMessage.success('删除成功')
  })
}

const handleToggleStatus = (row: Product) => {
  const newStatus = row.status === 'on' ? 'off' : 'on'
  productStore.updateProduct({ ...row, status: newStatus })
}

const handleUploadSuccess = (response: any) => {
  productForm.images.push(response.url)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (formType.value === 'add') {
        productStore.setProducts([...productStore.products, { 
          ...productForm,
          id: Date.now(),
          createdAt: new Date().toISOString()
        }])
      } else {
        productStore.updateProduct({ ...productForm })
      }
      
      dialogVisible.value = false
      ElMessage.success(formType.value === 'add' ? '添加成功' : '更新成功')
    }
  })
}

const handleSearch = () => {
  currentPage.value = 1
}

const resetFilter = () => {
  Object.assign(filterForm, {
    keyword: '',
    categoryId: '',
    status: '',
    minPrice: undefined,
    maxPrice: undefined
  })
  currentPage.value = 1
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

const handleViewDetail = (row: Product) => {
  currentProduct.value = row
  detailVisible.value = true
}

const handleExport = () => {
  // 实现导出功能
  ElMessage.success('导出成功')
}

// 辅助函数
const getCategoryName = (categoryId?: number) => {
  if (!categoryId) return ''
  return productStore.categories.find(c => c.id === categoryId)?.name || ''
}

const getShippingMethodText = (method?: string) => {
  const methods = {
    express: '快递',
    self: '自提',
    both: '快递和自提'
  }
  return method ? methods[method as keyof typeof methods] : ''
}

const formatDate = (date?: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.filter-section {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mx-2 {
  margin: 0 8px;
}

.header-actions {
  display: flex;
  gap: 12px;
}
</style> 